package com.tjmc.recruit.user.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tjmc.company.api.entity.AutoRefreshLogEntity;
import com.tjmc.company.api.entity.CompanyCollectRecordsEntity;
import com.tjmc.company.api.feign.AutoRefreshService;
import com.tjmc.company.api.feign.CompanyInfoService;
import com.tjmc.recruit.admin.api.entity.PlatformUserInfoEntity;
import com.tjmc.recruit.admin.api.enums.PlatUserTypeEnum;
import com.tjmc.recruit.admin.api.feign.RemoteSessionService;
import com.tjmc.recruit.admin.api.feign.RemoteUserService;
import com.tjmc.recruit.common.core.constant.CommonConstants;
import com.tjmc.recruit.common.core.constant.SecurityConstants;
import com.tjmc.recruit.common.core.exception.CheckedException;
import com.tjmc.recruit.common.core.exception.ErrorCodes;
import com.tjmc.recruit.common.core.util.MsgUtils;
import com.tjmc.recruit.common.core.util.R;
import com.tjmc.recruit.common.security.util.SecurityUtils;
import com.tjmc.recruit.finance.api.dto.AccountChangeDTO;
import com.tjmc.recruit.finance.api.entity.MemberPersonalEquityConfEntity;
import com.tjmc.recruit.finance.api.entity.PlatformUserAccountEntity;
import com.tjmc.recruit.finance.api.entity.UsageRecordsEntity;
import com.tjmc.recruit.finance.api.enums.ChangeMehtodEnum;
import com.tjmc.recruit.finance.api.enums.UsageServiceTypeEnum;
import com.tjmc.recruit.finance.api.enums.UsageTypeEnum;
import com.tjmc.recruit.finance.api.feign.MemberInfoService;
import com.tjmc.recruit.finance.api.feign.RemoteAccountService;
import com.tjmc.recruit.finance.api.feign.RemoteUsageRecordsService;
import com.tjmc.recruit.finance.api.vo.MemberInfoVO;
import com.tjmc.recruit.user.dto.PersonalInfo;
import com.tjmc.recruit.user.dto.ResumeSearchDTO;
import com.tjmc.recruit.user.entity.*;
import com.tjmc.recruit.user.mapper.PersonalBasicInfoMapper;
import com.tjmc.recruit.user.service.*;
import com.tjmc.recruit.user.vo.ResumeInfoVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.util.*;

@Service
@Slf4j
@RequiredArgsConstructor
public class PersonalResumeServiceImpl implements IResumeService {
    private final PersonalBasicInfoService personalBasicInfoService;
    private final PersonalJobIntentInfoService personalJobIntentInfoService;
    private final PersonalTrainingInfoService personalTrainingInfoService;
    private final PersonalEducationInfoService personalEducationInfoService;
    private final PersonalProgramInfoService personalProgramInfoService;
    private final PersonalSelfDescriptionService personalSelfDescriptionService;
    private final PersonalWorkExperienceInfoService personalWorkExperienceInfoService;


    private final PersonalBasicInfoMapper personalBasicInfoMapper;

    private final RemoteUsageRecordsService remoteUsageRecordsService;
    private final RemoteUserService remoteUserService;
    private final RemoteAccountService remoteAccountService;
    private final CompanyInfoService companyInfoService;
    private final AutoRefreshService autoRefreshLogService;
    private final MemberInfoService memberInfoService;
    private final RemoteSessionService sessionService;

    @Override
    public PersonalInfo getPersonalInfoByUserId(String userId, Long companyId) {
        if (StrUtil.isBlank(userId)) {
            throw new CheckedException("用户ID不能为空");
        }
        PersonalBasicInfoEntity basicInfo = personalBasicInfoService.getOne(new LambdaQueryWrapper<PersonalBasicInfoEntity>().eq(PersonalBasicInfoEntity::getAccountId, userId));
        List<PersonalJobIntentInfoEntity> jobIntentInfo = personalJobIntentInfoService.list(new LambdaQueryWrapper<PersonalJobIntentInfoEntity>().eq(PersonalJobIntentInfoEntity::getAccountId, userId));
        List<PersonalTrainingInfoEntity> trainingList = personalTrainingInfoService.list(new LambdaQueryWrapper<PersonalTrainingInfoEntity>().eq(PersonalTrainingInfoEntity::getAccountId, userId));
        List<PersonalEducationInfoEntity> educationList = personalEducationInfoService.list(new LambdaQueryWrapper<PersonalEducationInfoEntity>().eq(PersonalEducationInfoEntity::getAccountId, userId));
        List<PersonalProgramInfoEntity> programList = personalProgramInfoService.list(new LambdaQueryWrapper<PersonalProgramInfoEntity>().eq(PersonalProgramInfoEntity::getAccountId, userId));
        PersonalSelfDescriptionEntity selfDescription = personalSelfDescriptionService.getOne(new LambdaQueryWrapper<PersonalSelfDescriptionEntity>().eq(PersonalSelfDescriptionEntity::getAccountId, userId));
        List<PersonalWorkExperienceInfoEntity> workExerienceList = personalWorkExperienceInfoService.list(new LambdaQueryWrapper<PersonalWorkExperienceInfoEntity>().eq(PersonalWorkExperienceInfoEntity::getAccountId, userId));

        PersonalInfo personalInfo = new PersonalInfo();
        personalInfo.setPersonalBasicInfo(basicInfo);
        personalInfo.setPersonalJobIntentInfo(jobIntentInfo);
        personalInfo.setTrainingList(trainingList);
        personalInfo.setEducationList(educationList);
        personalInfo.setProgramList(programList);
        personalInfo.setPersonalSelfDescriptionInfo(selfDescription);
        personalInfo.setWorkExperienceList(workExerienceList);
        //判断是否被企业收藏
        if (companyId != null && companyId != 0) {
            R<CompanyCollectRecordsEntity> collectResume = companyInfoService.getCollectResume(companyId, Long.valueOf(userId), SecurityConstants.FROM_IN);
            if (collectResume.getCode() != CommonConstants.SUCCESS) {
                throw new CheckedException(collectResume.getMsg());
            }
            CompanyCollectRecordsEntity data = collectResume.getData();
            personalInfo.setCollectByCompany(data != null);
            personalInfo.setCollectRecordsId(data == null ? null : String.valueOf(data.getId()));
        }
        // 判断是否与当前企业沟通过
        String name = SecurityUtils.getUser().getName();
        R<PlatformUserInfoEntity> platformedUser = remoteUserService.platformUser(name, SecurityConstants.FROM_IN);
        PlatformUserInfoEntity platformUserInfo = platformedUser.getData();
        if (platformUserInfo != null && platformUserInfo.getUserType().equals(PlatUserTypeEnum.COMPANY)) {
            R<Boolean> chat = sessionService.isChat(Long.valueOf(userId), platformUserInfo.getId(), SecurityConstants.FROM_IN);
            personalInfo.setIsChat(chat.getCode() == CommonConstants.SUCCESS);
        } else {
            personalInfo.setIsChat(false);
        }
        return personalInfo;
    }

    @Override
    public Page<ResumeInfoVO> searchPage(Page page, ResumeSearchDTO searchDTO) {
        // 1. 组合查询条件
        Map<String, Object> map = buildResumeSearchParams(searchDTO);
        // 2. 构造分页条件
        Page<ResumeInfoVO> voPage = new Page<>(page.getCurrent(), page.getSize());
        return personalBasicInfoMapper.getResumeInfoPage(voPage, map);
    }

    private Map<String, Object> buildResumeSearchParams(ResumeSearchDTO searchDTO) {
        Map<String, Object> params = new HashMap<>();
        R<PlatformUserInfoEntity> platformedUser = remoteUserService.platformUser(SecurityUtils.getUser().getName(), SecurityConstants.FROM_IN);
        params.put("companyUserId", platformedUser.getData().getId());
        //岗位
        if (StrUtil.isNotBlank(searchDTO.getJobName())) {
            params.put("jobName", searchDTO.getJobName());
        }
        //工作经验
        if (StrUtil.isNotBlank(searchDTO.getWorkExperience())) {
            params.put("workExperience", searchDTO.getWorkExperience());
        }
        //年龄开始
        if (ObjectUtil.isNotNull(searchDTO.getAgeStart()) && searchDTO.getAgeStart() > 0) {
            params.put("ageStart", searchDTO.getAgeStart());
        }
        //年龄结束
        if (ObjectUtil.isNotNull(searchDTO.getAgeEnd()) && searchDTO.getAgeEnd() > 0) {
            params.put("ageEnd", searchDTO.getAgeEnd());
        }
        //学历
        if (StrUtil.isNotBlank(searchDTO.getDegree())) {
            params.put("degree", searchDTO.getDegree());
        }
        //是否有照片
        if (StrUtil.isNotBlank(searchDTO.getHasPicture())) {
            params.put("hasPicture", searchDTO.getHasPicture());
        }
        //性别
        if (StrUtil.isNotBlank(searchDTO.getGender())) {
            params.put("gender", searchDTO.getGender());
        }
        //当前状态：及时到岗与否
        if (StrUtil.isNotBlank(searchDTO.getCurrentStatus())) {
            params.put("currentStatus", searchDTO.getCurrentStatus());
        }
        //工作性质：兼职、全职
        if (StrUtil.isNotBlank(searchDTO.getJobProperties())) {
            params.put("jobProperties", searchDTO.getJobProperties());
        }
        return params;
    }


    public R<String> checkPhoneByAccountId(Long accountId, BigDecimal eCoinNum) {
        // 1.查询被查看用户信息
        PersonalBasicInfoEntity basicInfo = personalBasicInfoService.getOne(new LambdaQueryWrapper<PersonalBasicInfoEntity>().eq(PersonalBasicInfoEntity::getAccountId, accountId));
        if (basicInfo == null) {
            return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_USER_QUERY_ERROR));
        }
        // 2。查询调用者信息，这里取当前登录用户信息
//        Long companyUserId = SecurityUtils.getUser().getId();
        R<PlatformUserInfoEntity> platformedUser = remoteUserService.platformUser(SecurityUtils.getUser().getName(), SecurityConstants.FROM_IN);
        PlatformUserInfoEntity platformUserInfo = platformedUser.getData();
        if (platformUserInfo == null) {
            return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_USER_QUERY_ERROR));
        }
        // 3. 修改账户数据
        AccountChangeDTO accountChangeDTO = new AccountChangeDTO();
        //修改账户ID
        accountChangeDTO.setAccountId(platformUserInfo.getId());
        //变更数量
        accountChangeDTO.setChangeValue(eCoinNum);
        //修改方法
        accountChangeDTO.setChangeMethod(ChangeMehtodEnum.SUBTRACT.name());
        //变更类型
        accountChangeDTO.setUsageType(UsageTypeEnum.E_COIN);
        remoteAccountService.changeAccountInfo(accountChangeDTO, SecurityConstants.FROM_IN);
        // 4. 新增一条E币消费记录
        UsageRecordsEntity usageRecordsEntity = new UsageRecordsEntity();
        usageRecordsEntity.setUsageType(UsageTypeEnum.E_COIN);
        //发起调用者：这里传当前登录用户（企业用户）ID
        usageRecordsEntity.setUsageAccountId(platformUserInfo.getId());
        usageRecordsEntity.setAmount(eCoinNum);
        //被查看者，传入参数查询用户ID
        usageRecordsEntity.setServiceId(basicInfo.getAccountId());
        usageRecordsEntity.setServiceName(basicInfo.getName());
        usageRecordsEntity.setServiceType(UsageServiceTypeEnum.CHECK_PHONE);
        usageRecordsEntity.setUsageCompanyId(platformUserInfo.getCompanyId());
        remoteUsageRecordsService.add(usageRecordsEntity, SecurityConstants.FROM_IN);
        // 5. 用户手机号返回
        return R.ok(basicInfo.getPhone());
    }

    @Override
    public R<byte[]> createPdf(String userId) {
//        PersonalInfo personalInfo = getPersonalInfoByUserId(userId);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

//        PdfWriter pdfWriter = new PdfWriter(outputStream);
//        PdfDocument pdfDocument = new PdfDocument(pdfWriter);
//        Document document = new Document(pdfDocument);
//
//        addSection(document, "基础信息", personalInfo.getPersonalBasicInfo().getName());
//
//        document.close();
        return R.ok(outputStream.toByteArray());
    }

    @Override
    public Page<ResumeInfoVO> getRecommendsResumePage(Page page, Long companyId) {
        Page<ResumeInfoVO> objectPage = new Page<>(page.getCurrent(), page.getSize());
        Map<String, Object> map = new HashMap<>();
        map.put("companyId", companyId);
        return personalBasicInfoMapper.getRecommendsResumePage(objectPage, map);
    }

    @Override
    public R refreshResume(Long accountId) {
//        // 1. 变更账户
//        AccountChangeDTO accountChangeDTO = new AccountChangeDTO();
//        accountChangeDTO.setAccountId(accountId);
//        accountChangeDTO.setChangeValue(BigDecimal.ONE);
//        accountChangeDTO.setChangeMethod(ChangeMehtodEnum.SUBTRACT.name());
//        accountChangeDTO.setUsageType(UsageTypeEnum.E_COIN);
//        R r = remoteAccountService.changeAccountInfo(accountChangeDTO, SecurityConstants.FROM_IN);
//        if (r.getCode() != CommonConstants.SUCCESS) {
//            return R.failed(r.getMsg());
//        }
//        // 2. 新增消费记录
//        UsageRecordsEntity usageRecordsEntity = new UsageRecordsEntity();
//        usageRecordsEntity.setUsageType(UsageTypeEnum.E_COIN);
//        //发起调用者
//        usageRecordsEntity.setUsageAccountId(accountId);
//        usageRecordsEntity.setAmount(BigDecimal.ONE);
//        //被查看者，传入简历用户ID
//        usageRecordsEntity.setServiceId(accountId);
//        usageRecordsEntity.setServiceName("");
//        usageRecordsEntity.setServiceType(UsageServiceTypeEnum.RESUME_REFRESH);
//        usageRecordsEntity.setUsageCompanyId(null);
//        remoteUsageRecordsService.add(usageRecordsEntity, SecurityConstants.FROM_IN);
        // 日刷新次数限制
        AutoRefreshLogEntity countParam = new AutoRefreshLogEntity();
        countParam.setPersonalUserId(String.valueOf(accountId));
        R<Integer> dayCount = autoRefreshLogService.getDayCount(countParam, SecurityConstants.FROM_IN);
        Integer count = dayCount.getData();
        // 查询会员权益
        R<MemberInfoVO> accountInfo = memberInfoService.getAccountInfo(accountId, SecurityConstants.FROM_IN);
        if (accountInfo.getCode() != CommonConstants.SUCCESS) {
            return R.failed(accountInfo.getMsg());
        }
        MemberInfoVO infoVO = accountInfo.getData();
        MemberPersonalEquityConfEntity personalEquityConf = infoVO.getPersonalEquityConf();
        if (ObjectUtil.isNull(personalEquityConf)) {
            return R.failed("会员权益信息为空");
        }
        Integer resumeRefreshDayNum = personalEquityConf.getResumeRefreshDayNum();
        if (Objects.equals(count, resumeRefreshDayNum)) {
            return R.failed("刷新次数已达上限");
        }
        // 3. 新增刷新日志
        AutoRefreshLogEntity autoRefreshLogEntity = new AutoRefreshLogEntity();
        autoRefreshLogEntity.setRefreshTarget("RESUME");
        autoRefreshLogEntity.setRefreshType("MANUAL");//手动
        autoRefreshLogEntity.setPersonalUserId(String.valueOf(accountId));
        autoRefreshLogService.save(autoRefreshLogEntity, SecurityConstants.FROM_IN);
        // 4 刷新简历时间
        boolean update = personalBasicInfoService.update(new LambdaUpdateWrapper<PersonalBasicInfoEntity>()
                .eq(PersonalBasicInfoEntity::getAccountId, accountId).set(PersonalBasicInfoEntity::getUpdateAt, new Date()));
        if (!update) {
            return R.failed("更新失败");
        }
        return R.ok();
    }
}
